package cn.lijiajia3515.cairo.common;

import cn.lijiajia3515.cairo.auth.modules.account.FindAccountParam;
import cn.lijiajia3515.cairo.auth.modules.account.Account;
import cn.lijiajia3515.cairo.auth.modules.account.AccountRClient;
import cn.lijiajia3515.cairo.mongo.data.CreatedMongo;
import cn.lijiajia3515.cairo.mongo.data.LastModifiedMongo;
import cn.lijiajia3515.cairo.mongo.data.MetaMongo;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toMap;

public abstract class BaseService {
	protected final AccountRClient userClient;

	protected BaseService(AccountRClient userClient) {
		this.userClient = userClient;
	}

	public Stream<String> getMetaAccountIds(MetaMongo metadata) {
		return Optional.ofNullable(metadata)
			.map(x -> Stream.of(
					Optional.ofNullable(x.getCreated()).map(CreatedMongo::getAccountId).orElse(null),
					Optional.ofNullable(x.getLastModified()).map(LastModifiedMongo::getAccountId).orElse(null)
				)
				.filter(Objects::nonNull))
			.orElse(Stream.empty());
	}

	public Set<String> getMetaAccountIds(Collection<MetaMongo> meta) {
		return Optional.ofNullable(meta)
			.stream()
			.flatMap(Collection::stream)
			.flatMap(this::getMetaAccountIds)
			.collect(Collectors.toSet());
	}

	public Map<String, Account> getAccountMap(Collection<MetaMongo> meta, Map<String, String> extensionMap) {
		return Optional.of(getMetaAccountIds(meta))
			.filter(x -> !x.isEmpty())
			.map(x ->
				userClient.find(FindAccountParam.builder().extension(extensionMap).uids(x).build())
					.stream()
					.collect(toMap(Account::getId, y -> y)))
			.orElse(Collections.emptyMap());
	}
}
